<style>
.in1 {
  margin-left: 7px;
}
.aa11 {
  cursor: pointer;
}
.ivu-table-overflowX {
    overflow-x: hidden;
}
.page {
  text-align: center;
  margin-top: 7px;
}
.page1 {
  text-align: center;
  margin-top: 15px;
  overflow-x: hidden;
}
.demo-drawer-profile {
  font-size: 14px;
}
.demo-drawer-profile .ivu-col {
  margin-bottom: 12px;
}
.myrole {
  margin-left: 10px;
}
</style>
<template>
  <div>
    <Breadcrumb>
      <BreadcrumbItem to="/main/myInfo">
        <e-icon icon-name="el-icon-s-home"></e-icon>主页
      </BreadcrumbItem>
      <BreadcrumbItem>
        <e-icon icon-name="el-icon-setting"></e-icon>系统管理
      </BreadcrumbItem>
      <BreadcrumbItem>角色管理 </BreadcrumbItem>
    </Breadcrumb>

    <Divider />

    <Button type="primary" icon="ios-ionitron-outline" @click="open"
      >添加角色</Button
    >

    <Modal
      ref="modal1"
      :loading="isLoading"
      v-model="modal1"
      title="添加角色"
      @on-ok="addRole('rolePo')"
      @on-cancel="cancel"
    >
      <Form
        ref="rolePo"
        :model="rolePo"
        :rules="ruleValidate"
        :label-width="80"
      >
        <FormItem label="角色名称" prop="name">
          <Input
            clearable
            v-model="rolePo.name"
            placeholder="请输入角色名称"
          ></Input>
        </FormItem>
        <FormItem label="角色状态" prop="status">
          <i-switch
            true-color="#13ce66"
            false-color="#ff4949"
            size="large"
            :true-value="0"
            :false-value="1"
            v-model="rolePo.status"
          >
            <span slot="open">正常√</span>
            <span slot="close">禁用×</span>
          </i-switch>
        </FormItem>
        <FormItem label="角色菜单" prop="menuIdList">
          <el-select
            multiple
            clearable
            placeholder="请选择"
            ref="selectUpResId"
            style="width: 407px"
          >
            <el-option hidden key="upResId"> </el-option>
            <el-tree
              :data="menuData"
              show-checkbox
              node-key="id"
              ref="tree"
              :props="defaultProps"
              :expand-on-click-node="false"
              :check-on-click-node="true"
            >
            </el-tree>
          </el-select>
        </FormItem>

        <FormItem label="角色描述" prop="rdesc">
          <Input
            v-model="rolePo.rdesc"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 5 }"
            placeholder="请输入角色描述"
          ></Input>
        </FormItem>
      </Form>
    </Modal>

    <Modal
      ref="modal2"
      :loading="isLoading"
      v-model="modal2"
      title="修改角色"
      @on-ok="updateRole('rolePo2')"
      @on-cancel="cancel"
    >
      <Form
        ref="rolePo2"
        :model="rolePo"
        :rules="ruleValidate2"
        :label-width="80"
      >
        <FormItem label="角色名称" prop="name">
          <Input
            clearable
            v-model="rolePo.name"
            placeholder="请输入角色名称"
          ></Input>
        </FormItem>
        <FormItem label="角色状态" prop="status">
          <i-switch
            true-color="#13ce66"
            false-color="#ff4949"
            size="large"
            :true-value="0"
            :false-value="1"
            v-model="rolePo.status"
          >
            <span slot="open">正常</span>
            <span slot="close">禁用</span>
          </i-switch>
        </FormItem>
        <FormItem label="角色菜单" prop="menuIdIdList">
          <el-select
            multiple
            clearable
            placeholder="请选择菜单"
            ref="selectUpResId2"
            style="width: 407px"
          >
            <el-option hidden key="upResId"> </el-option>
            <el-tree
              :data="menuData"
              show-checkbox
              check-strictly="true"
              node-key="id"
              ref="tree2"
              :props="defaultProps"
              :expand-on-click-node="false"
              :check-on-click-node="true"
            >
            </el-tree>
          </el-select>
        </FormItem>

        <FormItem label="角色描述" prop="rdesc">
          <Input
            v-model="rolePo.rdesc"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 5 }"
            placeholder="请输入角色描述"
          ></Input>
        </FormItem>
      </Form>
    </Modal>

    <Input
      class="in1"
      clearable
      v-model="roleQo.name"
      placeholder="请输入角色名称"
      style="width: 200px"
    />
    <Select
      class="in1"
      v-model="roleQo.status"
      clearable
      style="width: 200px"
      placeholder="请选择角色状态"
    >
      <Option value="0">正常</Option>
      <Option value="1">禁用</Option>
    </Select>
    <Button class="in1" type="primary" icon="ios-search" @click="selectRole"
      >搜索</Button
    >
    <Button class="in1" icon="md-close" @click="reset">清除</Button>

    <Table
      context-menu
      show-context-menu
      class="page1"
      ref="selection"
      border
      :columns="columns1"
      :data="data.records"
      
      @on-selection-change="checkRole"
      @on-contextmenu="handleContextMenu"
      :loading="loading"
    >
      <template slot="contextMenu">
        <DropdownItem @click.native="handleContextMenuEdit">修改</DropdownItem>
        <DropdownItem
          @click.native="handleContextMenuDelete"
          style="color: #ed4014"
          >删除</DropdownItem
        >
      </template>
    </Table>
    <Button
      class="page1"
      type="error"
      ghost
      @click="ifDeleteAll"
      icon="ios-trash"
      >删除所选</Button
    >
    <Button
      class="page1"
      type="warning"
      ghost
      @click="disabledCheckRole"
      icon="ios-switch"
      >注销/恢复所选</Button
    >
    <Page
      class="page"
      :total="data.total"
      :current="data.current"
      :page-size="6"
      :page-size-opts="pagesizeopts"
      @on-page-size-change="sizeChange"
      @on-change="changePage"
      show-elevator
      show-total
      show-sizer
    />

    <Drawer :closable="false" placement="left" width="640" v-model="value4">
      <h4 :style="pStyle">角色详情信息</h4>
      <div class="demo-drawer-profile">
        <Row>
          <Col span="12"> 角色名称 ：{{ this.RoleUserMenuPo.name }}</Col>
          <Col span="12">
            角色状态 ：<Tag
              size="large"
              type="dot"
              color="success"
              v-if="this.RoleUserMenuPo.status == 0"
              >正常</Tag
            >
            <Tag type="dot" color="error" v-if="this.RoleUserMenuPo.status == 1"
              >禁用</Tag
            >
          </Col>
        </Row>
        <Row> 角色描述 ：{{ this.RoleUserMenuPo.rdesc }} </Row>
      </div>
      <Divider />
      <h4 :style="pStyle">拥有菜单信息</h4>
      <div
        class="demo-drawer-profile"
        v-if="
          this.RoleUserMenuPo.menuList !== undefined &&
          this.RoleUserMenuPo.menuList != null &&
          this.RoleUserMenuPo.menuList.length > 0
        "
      >
        <Tag
          style="margin: 10px"
          v-for="(item, index) in RoleUserMenuPo.menuList"
          :key="index"
          type="dot"
          color="primary"
          >{{ item.name }}</Tag
        >
      </div>
      <div class="demo-drawer-profile" v-else><h1>暂无菜单信息</h1></div>
      <Divider />
      <h4 :style="pStyle">拥有用户信息</h4>

      <div
        class="demo-drawer-profile"
        v-if="
          this.RoleUserMenuPo.userList !== undefined &&
          this.RoleUserMenuPo.userList != null &&
          this.RoleUserMenuPo.userList.length > 0
        "
      >
        <p>
          🤫:若需管理用户，请前往<router-link to="/main/User"
            >用户管理</router-link
          >
        </p>
        <Card
          style="width: 130px; float: left; margin: 10px; height: 95px"
          v-for="(items, index) in RoleUserMenuPo.userList"
          :key="index"
        >
          <div style="text-align: center">
            <Avatar style="color: #f56a00; background-color: #e3f2fd">{{
              items.name.substr(0, 1)
            }}</Avatar>
            <h4>{{ items.name }}</h4>
            <h4>{{ items.account }}</h4>
          </div>
        </Card>
      </div>
      <div v-else class="demo-drawer-profile">
        <h1>暂无用户信息</h1>
      </div>
    </Drawer>
  </div>
</template>

<script>
export default {
  inject: ["reload"],
  components: {},
  data() {
    return {
      //表格加载
      loading: true,
      //每页展示条数
      pagesizeopts: [6, 10, 15, 20],
      //下拉框显示的菜单名
      parentName: "",
      //树形组件需要的数据对应
      defaultProps: {
        children: "children",
        label: "name",
      },
      //存放下拉菜单
      menuData: [],
      //存放查询用户roleVo的信息
      data: {},
      //查询用户的查询条件
      roleQo: {
        pageSize: 6,
        pageIndex: 1,
      },
      //添加角色确定按钮的一直加载，添加信息不符合要求时不会关闭弹窗
      isLoading: true,
      //添加角色->是否打开弹窗
      modal1: false,
      //修改角色->是否打开弹窗
      modal2: false,
      //添加角色时存储用户的信息
      rolePo: {
        menuIdList: [],
      },
      //存储多选时角色id
      roleIdList: [],
      //存储角色的详情信息
      RoleUserMenuPo: {},
      //角色详情页面的style
      pStyle: {
        fontSize: "16px",
        color: "rgba(0,0,0,0.85)",
        lineHeight: "24px",
        display: "block",
        marginBottom: "16px",
      },
      //是否显示角色详情页
      value4: false,
      //右键表格的行数
      contextLine: "",
      //添加角色时的表单验证
      ruleValidate: {
        name: [
          { required: true, message: "角色名称不能为空", trigger: "blur" },
        ],
        // status: [
        //   {
        //     required: true,
        //     message: "角色状态不能为空",
        //   },
        // ],
      },
      //修改角色时的表单验证
      ruleValidate2: {
        name: [
          { required: true, message: "角色名称不能为空", trigger: "blur" },
        ],
        status: [
          {
            required: true,
            message: "角色状态不能为空",
          },
        ],
      },
      //角色的表格
      columns1: [
        {
          width: 80,
          type: "selection",
        },
        {
          title: "ID",
          key: "id",
          width: 80,
        },
        {
          title: "角色名称",
          key: "name",
          width: 230,
        },
        {
          title: "角色描述",
          key: "rdesc",
          width: 380,
        },
        {
          title: "角色状态",
          key: "statusShow",
          width: 120,
          align: "center",
          render: (h, params) => {
            const row = params.row;
            return h(
              "i-switch",
              {
                props: {
                  size: "large",
                  trueColor: "#13ce66",
                  falseColor: "#ff4949",
                  value: row.status === 0,
                },
                nativeOn: {
                  click: () => {
                    this.disabledRole(params.index);
                  },
                },
              },
              [
                h("span", { slot: "open" }, "正常"),
                h("span", { slot: "close" }, "禁用"),
              ]
            );
          },
        },
        {
          title: "操作",
          align: "center",
          render: (h, params) => {
            let ifStatus;
            if (params.row.status == 0) {
              ifStatus = true;
            } else if (params.row.status == 1) {
              ifStatus = false;
            }
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small",
                    icon: "md-glasses",
                  },
                  style: {
                    id: "btn1",
                    marginLeft: "12px",
                  },
                  on: {
                    click: () => {
                      this.show(params.index);
                    },
                  },
                },
                "详情"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "info",
                    size: "small",
                    icon: "md-create",
                  },
                  style: {
                    marginLeft: "12px",
                  },
                  on: {
                    click: () => {
                      this.open2(params.index);
                    },
                  },
                },
                "修改"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small",
                    icon: "ios-trash-outline",
                  },
                  style: {
                    marginLeft: "12px",
                  },
                  on: {
                    click: () => {
                      this.ifDelete(params.index);
                    },
                  },
                },
                "删除"
              ),
              // ifStatus
              //   ? h(
              //       "Button",
              //       {
              //         props: {
              //           type: "warning",
              //           size: "small",
              //           icon: "ios-switch-outline",
              //         },
              //         style: {
              //           marginLeft: "6px",
              //         },
              //         on: {
              //           click: () => {
              //             this.disabledRole(params.index);
              //           },
              //         },
              //       },
              //       "注销"
              //     )
              //   : h(
              //       "Button",
              //       {
              //         props: {
              //           type: "success",
              //           size: "small",
              //           icon: "ios-switch-outline",
              //         },
              //         style: {
              //           marginLeft: "6px",
              //         },
              //         on: {
              //           click: () => {
              //             this.disabledRole(params.index);
              //           },
              //         },
              //       },
              //       "恢复"
              //     ),
            ]);
          },
        },
      ],
    };
  },
  created() {
    //页面加载时
    //查询角色
    this.selectRole();
    //页面加载时
    //查询菜单
    this.selectMenu();
  },
  methods: {
    //查询菜单
    selectMenu() {
      this.$axios
        .get("/menu/ListTreeData2")
        .then((result) => {
          //赋值给菜单信息
          this.menuData = result.data.data;
        })
        .catch((err) => {});
    },
    //查询角色
    selectRole() {
      this.loading = true;
      this.$axios
        .post("/role/roleListPages", this.roleQo)
        .then((result) => {
          this.data = result.data.data;
          this.loading = false;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //打开添加角色弹窗
    open() {
      this.modal1 = true;
    },
    //打开修改角色弹窗
    open2(index) {
      this.$axios
        .get("/role/selectRoleById", {
          params: {
            id: this.data.records[index].id,
          },
        })
        .then((result) => {
          this.rolePo = {
            menuIdList: [],
          };
          this.rolePo.id = result.data.data.id;
          this.rolePo.name = result.data.data.name;
          this.rolePo.status = result.data.data.status;
          this.rolePo.rdesc = result.data.data.rdesc;
          result.data.data.menuList.forEach((element) => {
            this.rolePo.menuIdList.push(element.id);
          });
          this.$refs.tree2.setCheckedKeys(this.rolePo.menuIdList);
          this.modal2 = true;

          console.log(this.rolePo.roleIdList);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //添加角色
    addRole(name) {
      this.$refs[name].validate((valid) => {
        this.rolePo.menuIdList = this.$refs.tree
          .getCheckedKeys()
          .concat(this.$refs.tree.getHalfCheckedKeys());
        //验证输入的角色信息是否正确
        if (valid) {
          this.$axios
            .post("/role/addRole", this.rolePo)
            .then((result) => {
              if (result.data.code == 0) {
                this.$Message.success({
                  duration: 2.5,
                  background: true,
                  content: "添加成功",
                });
                //插入数据成功更新查询
                this.selectRole();
                //清空上次保存的角色信息
                this.rolePo = {
                  menuIdList: [],
                };
                //清空下拉框选中
                this.$refs.tree.setCheckedKeys([]);
                this.modal1 = false;
              } else {
                this.$Message.error({
                  duration: 2.5,
                  background: true,
                  content: "添加失败",
                });
              }
            })
            .catch((err) => {
              console.log(err);
            });
        }
        //若验证数据错误，不关闭弹窗
        else {
          setTimeout(() => {
            this.isLoading = false;
            this.$nextTick(() => {
              this.isLoading = true;
            });
          }, 100);
          return;
        }
      });
    },
    //改变页数时
    changePage(e) {
      //变更查询时的页数条件
      this.roleQo.pageIndex = e;
      this.selectRole();
    },
    //多选选中角色
    checkRole(e) {
      //先将选中id设为空，以免重复添加id
      this.roleIdList = [];
      console.log(e);
      //循环添加id
      e.forEach((element) => {
        this.roleIdList.push(element.id);
      });
      console.log(this.roleIdList);
    },

    //弹框问是否删除多选
    ifDeleteAll() {
      if (
        this.roleIdList !== undefined &&
        this.roleIdList !== null &&
        this.roleIdList.length > 0
      ) {
        this.$Modal.confirm({
          title: "警告",
          content: "<p>你真的要删除这些角色么?</p>",
          onOk: () => {
            this.deleteCheckRole();
          },
          onCancel: () => {},
        });
      } else {
        this.$Message.warning({
          top: 30,
          duration: 2.5,
          background: true,
          content: "您未选择任何角色",
        });
      }
    },
    //删除选中的角色
    deleteCheckRole() {
      this.$axios
        .post("/role/deleteCheckRole", this.roleIdList)
        .then((result) => {
          if (result.data.code == 0) {
            this.$Message.success({
              duration: 2.5,
              background: true,
              content: "删除成功",
            });
            //删除成功，更新查询
            this.selectRole();
          } else {
            this.$Message.error({
              top: 30,
              duration: 2.5,
              background: true,
              content: "删除失败",
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //弹框问是否删除
    ifDelete(index) {
      this.$Modal.confirm({
        title: "警告",
        content: "<p>你真的要删除该角色么?</p>",
        onOk: () => {
          this.remove(index);
        },
        onCancel: () => {},
      });
    },
    //删除单个用角色
    remove(index) {
      this.$axios
        .get("/role/deleteRole", {
          params: {
            id: this.data.records[index].id,
          },
        })
        .then((result) => {
          if (result.data.code == 0) {
            this.$Message.success({
              top: 30,
              duration: 2.5,
              background: true,
              content: "删除成功",
            });
            //删除成功，更新查询
            this.selectRole();
          } else {
            this.$Message.error({
              top: 30,
              duration: 2.5,
              background: true,
              content: "删除失败",
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //注销/恢复选中用户
    disabledCheckRole() {
      if (
        this.roleIdList !== undefined &&
        this.roleIdList !== null &&
        this.roleIdList.length > 0
      ) {
        this.$axios
          .post("/role/disabledCheckRole", this.roleIdList)
          .then((result) => {
            if (result.data.code == 0) {
              this.$Message.success({
                top: 30,
                duration: 2.5,
                background: true,
                content: "操作成功",
              });
              //删除成功，更新查询
              this.selectRole();
            } else {
              this.$Message.error({
                top: 30,
                duration: 2.5,
                background: true,
                content: "操作失败",
              });
            }
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        this.$Message.warning({
          top: 30,
          duration: 2.5,
          background: true,
          content: "您未选择任何角色",
        });
      }
    }, //注销/恢复单个用户
    disabledRole(index) {
      this.$axios
        .get("/role/disabledRole", {
          params: {
            id: this.data.records[index].id,
          },
        })
        .then((result) => {
          if (result.data.code == 0) {
            this.$Message.success({
              top: 30,
              duration: 2.5,
              background: true,
              content: "操作成功",
            });
            //删除成功，更新查询
            this.selectRole();
          } else {
            this.$Message.error({
              top: 30,
              duration: 2.5,
              background: true,
              content: "操作失败",
            });
          }
        })
        .catch((err) => {
          get;
          console.log(err);
        });
    },
    //角色详情信息
    show(index) {
      this.value4 = true;
      this.$axios
        .get("/role/selectRoleById", {
          params: {
            id: this.data.records[index].id,
          },
        })
        .then((result) => {
          this.RoleUserMenuPo = result.data.data;
          console.log(this.RoleUserMenuPo);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //修改角色信息
    updateRole(name) {
      this.$refs[name].validate((valid) => {
        //验证输入的角色信息是否正确
        if (valid) {
          this.rolePo.menuIdList = this.$refs.tree2
            .getCheckedKeys()
            .concat(this.$refs.tree2.getHalfCheckedKeys());
          console.log(this.rolePo.menuIdList);
          this.$axios
            .post("/role/updateRole", this.rolePo)
            .then((result) => {
              if (result.data.code == 0) {
                this.$Message.success({
                  duration: 2.5,
                  background: true,
                  content: "修改成功",
                });
                //插入数据成功更新查询
                this.selectRole();
                //清空上次保存的角色信息
                this.rolePo = {
                  menuIdList: [],
                };
                this.modal2 = false;
                this.reload();
              } else {
                this.$Message.error({
                  duration: 2.5,
                  background: true,
                  content: "修改失败",
                });
              }
              console.log(result.data);
            })
            .catch((err) => {
              console.log(err);
            });
        }
        //若验证数据错误，不关闭弹窗
        else {
          setTimeout(() => {
            this.isLoading = false;
            this.$nextTick(() => {
              this.isLoading = true;
            });
          }, 100);
          return;
        }
      });
    },
    //关闭弹窗时，清除rolePo信息
    cancel() {
      this.rolePo = {
        menuIdList: [],
      };
      //清空下拉框选中
      this.$refs.tree.setCheckedKeys([]);
    },
    //右键表格时得到右键表格的位置
    handleContextMenu(row) {
      const index = this.data.records.findIndex(
        (item) => item.name === row.name
      );
      this.contextLine = index;
    },
    //右键修改信息
    handleContextMenuEdit() {
      this.open2(this.contextLine);
    },
    //右键删除角色
    handleContextMenuDelete() {
      this.$Modal.confirm({
        title: "警告",
        content: "<p>你真的要删除该角色么?</p>",
        onOk: () => {
          this.remove(this.contextLine);
        },
        onCancel: () => {},
      });
    },
    //改变页面显示数据大小时
    sizeChange(e){
      this.roleQo.pageSize = e;
      this.selectRole();
    },
    //清除查询条件
    reset() {
      (this.roleQo = {
        pageSize: this.roleQo.pageSize,
        pageIndex: 1,
      }),
        this.selectRole();
    },
  },
};
</script>